package com.example.musicserver.controller;

import com.example.musicserver.mapper.UserMapper;
import com.example.musicserver.model.User;
import com.example.musicserver.tools.Constant;
import com.example.musicserver.tools.ResponseBodyMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 18446
 * Date: 2022-07-22
 * Time: 11:17
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    @RequestMapping("/login")
    public ResponseBodyMessage<User> login(@RequestParam String username, @RequestParam String password, HttpServletRequest request){
/*        User userLogin = new User();
        userLogin.setUsername(username);
        userLogin.setPassword(password);*/

        User user = userMapper.selectByName(username);

        if(user == null){
            System.out.println("登陆失败");
            return new ResponseBodyMessage<>(-1,"登陆失败！",user);
        }else{
            boolean flg = bCryptPasswordEncoder.matches(password,user.getPassword());
            if(!flg){
                return new ResponseBodyMessage<>(-1,"用户名或密码错误！",user);
            }
            request.getSession().setAttribute(Constant.USERINFO_SESSION_KEY,user);
            return new ResponseBodyMessage<>(0,"登陆成功！",user);

        }

    }




    @RequestMapping("/login1")
    public ResponseBodyMessage<User> login1(@RequestParam String username, @RequestParam String password, HttpServletRequest request){
        User userLogin = new User();
        userLogin.setUsername(username);
        userLogin.setPassword(password);

        User user = userMapper.login(userLogin);

        if(user == null){
            System.out.println("登陆失败");
            return new ResponseBodyMessage(-1,"登陆失败！",userLogin);
        }else{
            request.getSession().setAttribute(Constant.USERINFO_SESSION_KEY,user);
            return new ResponseBodyMessage(0,"登陆成功！",userLogin);

        }

    }
}

























